﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ThoughtWorks.QRCode.Codec;

namespace JT_QRCode
{
    public partial class FQRCode : Form
    {
        public FQRCode()
        {
            InitializeComponent();
        }

        private void btn_create_Click(object sender, EventArgs e)
        {
            if (tbox_text.Text == "") return;

            ThoughtWorks.QRCode.Codec.QRCodeEncoder encoder = new QRCodeEncoder();
            encoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;//编码方式(注意：BYTE能支持中文，ALPHA_NUMERIC扫描出来的都是数字)
            encoder.QRCodeScale = Convert.ToInt16(cbox_px.SelectedItem);//大小(值越大生成的二维码图片像素越高)
            encoder.QRCodeVersion = 0;//版本(注意：设置为0主要是防止编码的字符串太长时发生错误)
            encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;//错误效验、错误更正(有4个等级)
            String qrdata = tbox_text.Text; //"二维码信息";
            System.Drawing.Bitmap bp = encoder.Encode(qrdata.ToString(), Encoding.GetEncoding("GB2312"));
            Image image = bp;
            pic_qrcode.Image = bp;
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            //保存二维码图片：
            SaveFileDialog sf = new SaveFileDialog();
            sf.Title = "选择保存文件位置";
            sf.Filter = "保存图片(*.png) |*.png|所有文件(*.*) |*.*";
            //设置默认文件类型显示顺序
            sf.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录
            sf.RestoreDirectory = true;
            if (sf.ShowDialog() == DialogResult.OK)
            {
                Image im = this.pic_qrcode.Image;
                //获得文件路径
                string localFilePath = sf.FileName.ToString();
                if (sf.FileName != "")
                {
                    string fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1);//获取文件名，不带路径
                    // newFileName = fileNameExt+DateTime.Now.ToString("yyyyMMdd")  ;//给文件名后加上时间
                    string FilePath = localFilePath.Substring(0, localFilePath.LastIndexOf("."));  //获取文件路径，带文件名,不带后缀
                    string fn = sf.FileName;
                    pic_qrcode.Image.Save(FilePath + "-" + DateTime.Now.ToString("yyyyMMdd") + ".png", System.Drawing.Imaging.ImageFormat.Png);

                }

            }
        }

        private void FQRCode_Load(object sender, EventArgs e)
        {
            pic_qrcode.Dock = DockStyle.Fill;

            for (int i = 1; i <= 20; i++)
                cbox_px.Items.Add(i.ToString());
            cbox_px.SelectedIndex = 4;
        }
    }
}
